#include "app/app_main.h"

#define HTTP_SERVER_ADDRESS  IP_ADDRESS(192,168,0,231)
#define HTTP_SERVER_PORT 		 18080

/*定义http客户端线程栈大小*/
#define HTTP_CLIENT_STACK_SIZE 4096
/*定义http客户端线程句柄*/
static TX_THREAD       http_client_thread;

static VOID http_thread_client_entry(ULONG thread_input);

void app_http_client_thread_create(VOID *first_unused_memory)
{
	UINT            status;
	char *pointer = TX_NULL;
	
	/* Allocate the stack for thread 1.  */
	tx_byte_allocate(first_unused_memory, (VOID **) &pointer, HTTP_CLIENT_STACK_SIZE, TX_NO_WAIT);
	if(pointer == TX_NULL)
	{
		PRINTF_Dbg("allocate http client thread stack failed..\r\n");
		
		return ;
	}
	/* Create the HTTP Client thread. */
	status = tx_thread_create(&http_client_thread, "HTTP Client", http_thread_client_entry, 0,  
									 pointer, HTTP_CLIENT_STACK_SIZE, 
									 6, 6, TX_NO_TIME_SLICE, TX_AUTO_START);
	if(status)
	{
		PRINTF_Dbg("create http client thread failed..\r\n");
		
		return ;
	}
}

VOID http_thread_client_entry(ULONG thread_input)
{
	UINT            status;
	NX_PACKET 			*packet_ptr;
	ULONG						len;
	NX_HTTP_CLIENT  my_client;
	
	for(;;)
	{
		/* Create an HTTP client instance.  */
		status = nx_http_client_create(&my_client, "HTTP Client", get_nx_ip_handle(), get_packet_pool_handle(), 600);

		/* Check status.  */
		if (status != NX_SUCCESS)
		{
			break;
		}
		
		nx_http_client_set_connect_port(&my_client,HTTP_SERVER_PORT);
		
		for(;;)
		{
			/* Use the 'NetX' service to send a GET request to the server (can only use IPv4 addresses). */
			status =  nx_http_client_get_start(&my_client, HTTP_SERVER_ADDRESS, "/index.html", 
																				 NX_NULL, 0, NX_NULL, NX_NULL, 50);

			/* Check status.  */
			if (status == NX_NOT_CONNECTED)
			{
				tx_thread_sleep(1000);
				
				continue;
			}
			else if (status == NX_SUCCESS)
			{
				status = nx_http_client_get_packet(&my_client,&packet_ptr,10);
				if(status == NX_SUCCESS)
				{
					nx_packet_length_get(packet_ptr,&len);
					PRINTF("len:%d\r\n%s\r\n",len,packet_ptr->nx_packet_prepend_ptr);
					
					nx_packet_release(packet_ptr);
				}
				
				break;
			}
		}
		
		nx_http_client_delete(&my_client);
		
		tx_thread_sleep(5000);
	}
	
	tx_thread_delete(tx_thread_identify());
}
